<?php
/**
 * Created by PhpStorm.
 *Author:huminghui
 * User: Administrator
 * Date: 2020/4/17
 * Time: 17:52
 */

namespace app\admin\controller;
use app\admin\model\User as UserModel;
use app\admin\model\AuthGroup as AuthGroupModel;
use think\Db;
use app\admin\validate\User as UserValidate;
class User extends Common
{
    public function lst(){
        return $this->fetch();
    }

    public function add(){
        $request =request();
        $data = $request->param();
        if($request->isGet()){
            $authGroupModel= new AuthGroupModel();
           $authGroup= $authGroupModel->readAllData();
           $this->assign("authGroup",$authGroup);
        }
        $userValidate=new UserValidate();
        if($request->isPost()){
            $userModel= new UserModel();
            if(!$userValidate->check($data)){
                $this->error($userValidate->getError());
            }
            $result= $userModel->saveData($data);
            if($result){
                $this->success('用户添加成功', 'lst');
            } else {
                $this->error('用户删除失败');
            }
        }
        return $this->fetch();
    }
    public function edit(){
        $request =request();
        $data = $request->param();
        $authGroupModel= new AuthGroupModel();
        if($request->isGet()){
           $userModel= Db::name("user")->alias("a")->join("auth_group_access c", "c.uid=a.id")->join("auth_group b","c.group_id = b.id")->field('a.id,a.username,c.group_id')->where("a.id",$data["id"])->find();
            $this->assign("user",$userModel);
            $authGroup= $authGroupModel->readAllData();
            $this->assign("authGroup",$authGroup);
        }
        $userValidate=new UserValidate();
        if($request->isPost()){
            $userModel= new UserModel();
            if(!$userValidate->check($data)){
                $this->error($userValidate->getError());
            }
            $result= $userModel->updateData($data);
            if($result){
                $this->success('用户更新成功', 'lst');
            } else {
                $this->error('用户更新失败');
            }
        }
        return $this->fetch();
    }
    public function listAll(){
        $userModel= new UserModel();
        $result= $userModel->readAllData();
        return json($result);
    }
    public function getGroupName(){
        $request=request();
        $data =$request->param();
        $result=Db::name("auth_group_access")->alias("a")->join("auth_group b","a.group_id = b.id")->field('b.title')->where($data)->find();
        return json($result);
    }
    public function del(){
        $request=request();
        $data=$request->param();
        $userModel= new UserModel();
        $result= $userModel->delDataById($data);
        if($result){
            $this->success('内容删除成功', 'lst');
        } else {
            $this->error('内容删除失败');
        }
    }
}